#include "unp.h"

static char read_buf[MAXLINE];

static int read_cnt;
static char* read_ptr;

static ssize_t my_read(int fd, char *ptr)
{
    if (read_cnt <= 0) {
again:
        if ( (read_cnt=read(fd, read_buf, sizeof(read_buf))) < 0) {
            if (errno == EINTR) {
                goto again;
            }
            return -1;
        } else if (read_cnt == 0) {
            return 0;
        }
        read_ptr = read_buf;
    }
    read_cnt--;
    *ptr = *read_ptr++;

    return 1;
}

ssize_t readline(int fd, void *vptr, size_t maxlen)
{
    char c, *ptr;
    size_t rc, n;

    ptr = (char*)vptr;
    for (n=0; n<maxlen; n++) {
        if ( (rc=my_read(fd, &c)) == 1) {
            *ptr++ = c;
            if (c == '\n') { /* newline is stored */
                break;
            }
        } else if (rc == 0) {
            *ptr = '\0';
            return n; /* eof */
        } else {
            return (-1);
        }
    }

    *ptr = '\0';
    return (n+1);
}

ssize_t Readline(int fd, void *vptr, size_t maxlen)
{
    ssize_t n;

    if ( (n=readline(fd, vptr, maxlen)) < 0) {
        err_sys("readline error");
    }
    return n;
}

